
//
//  WBComposeView.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/6.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
import pop
class WBComposeView: UIView {
    lazy var buttons : [UIButton] = [UIButton]()
    //记录按钮数组信息
    var infoArray:NSArray?
    var target:UIViewController?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setUI(){
        frame.size = UIScreen.main.bounds.size
        //backgroundColor = UIColor.blue
        addSubview(bgImage)
        addSubview(sloganImage)
        bgImage.snp_makeConstraints { (make)->Void in
            make.edges.equalTo(self)
        }
        sloganImage.snp_makeConstraints { (make)->Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        addChildButton()
    }
    
    func show(target:UIViewController){
//        let window = UIApplication.shared.keyWindow
//        window?.addSubview(self)
        self.target = target
        self.target?.view.addSubview(self)
        for (index,button) in self.buttons.enumerated(){
            animation(button: button, index: index, isUp: true)
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for (index,button) in self.buttons.reversed().enumerated(){
            animation(button: button, index: index, isUp: false)
            
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.7) {
            
            self.removeFromSuperview()
        }
    }
    func addChildButton(){
        let itemW : CGFloat = 80
        let itemH : CGFloat = 110
        let itemMargin = (WBScreenW - 3*itemW)/4
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let arr = NSArray(contentsOfFile: path)!
        infoArray = arr
        for i in 0..<arr.count{
            let button = WBComposeButton(textColor: UIColor.darkGray, fontSize: 14)
            //添加按钮点击事件
            button.addTarget(self, action: #selector(buttonClick(button:)), for: UIControlEvents.touchUpInside)
            let dict = arr[i] as! [String : String]
            button.setImage(UIImage(named: dict["icon"]!), for: UIControlState.normal)
            button.setTitle(dict["title"]!, for: UIControlState.normal)
            button.frame.size = CGSize(width: itemW, height: itemH)
            
            let col = i % 3
            let row = i / 3
            
            // 通过列数求出x值
            let x = CGFloat(col) * itemW + CGFloat(col + 1) * itemMargin
            // 通过行数求出y值
            let y = CGFloat(row) * itemH + WBScreenH
            // 设置按钮的位置
            button.frame.origin = CGPoint(x: x, y: y)
            
            addSubview(button)
            self.buttons.append(button)
        }
        
    }
    //按钮点击事件
    @objc private func buttonClick(button:UIButton){
        UIView.animate(withDuration: 0.5, animations: {
            for value in self.buttons{
                if button == value{
                    value.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else
                {
                    value.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
                value.alpha = 0.1
            }
            }) { (_) in
                let index = self.buttons.index(of: button) ?? 0
                let dick = self.infoArray![index] as! [String: String]
                if let clsName = dick["class"]{
                    let name = NSStringFromClass(WBComposeController.self)
                    print(name)
                    let type = NSClassFromString(clsName)! as! UIViewController.Type
                    let vc = type.init()
                    self.target?.present(WBNavigationController(rootViewController:vc), animated: true, completion: {
                        self.removeFromSuperview()
                    })
                    
                }
                
        }
    }
    //按钮执行动画
    func animation(button:UIButton,index:Int,isUp:Bool){
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        anim?.toValue = NSValue.init(cgPoint: CGPoint(x: button.center.x, y: button.center.y + (isUp ? -350 : 350)))
        anim?.springBounciness = 12
        anim?.springSpeed = 10
        anim?.beginTime = CACurrentMediaTime() + Double(index)*0.1
        button.pop_add(anim, forKey: nil)
    }
    //懒加载控件
    
    lazy var bgImage : UIImageView = {
        let image = UIImageView(image: UIImage.getScreenSnap()!.applyLightEffect())
        return image
    }()
    
    lazy var sloganImage:UIImageView = {
        let view = UIImageView(image: UIImage(named: "compose_slogan"))
        return view
    }()
    //截屏功能
    private func getScreenSnap() -> UIImage?{
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0)
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        return image
    }
}
